package adminservice

import (
	"context"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/security/code"
	"vpn-management-server/src/dao/admindao"
	"vpn-management-server/src/model/adminmodel"
)

func AddAdminService(ctx context.Context, admin *adminmodel.Admin, response *network.NetResponse) int64 {
	if ok := admindao.HasAdminByName(admin.Name); !ok {
		id, err := admindao.AddAdmin(admin)
		if err != nil {
			logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "add dao fail,err", err)
			response.Code = code.BAD_REQUEST
			response.ErrorMsg = "add admin fail"
			return -1
		}
		response.Code = code.SUCCESS
		logger.Logger.Infof("add admin %s success\n", admin.Name)
		return id
	} else {
		logger.Logger.Errorf("admin %s is already existed\n", admin.Name)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "admin is already existed"
		return -1
	}
}

func GetAdminRankService(ctx context.Context, request *network.NetRequest, response *network.NetResponse) int {
	if admin, ok := request.GetAttribute("admin").(*adminmodel.Admin); ok {
		return admin.Rank
	}
	logger.Logger.Error("get admin info from cache fail")
	return -1
}

func GetCurrAdminService(ctx context.Context, request *network.NetRequest, response *network.NetResponse) *adminmodel.Admin {
	if admin, ok := request.GetAttribute("admin").(*adminmodel.Admin); ok {
		return admin
	}
	return nil
}

func GetAdminByIdService(adminID int) (*adminmodel.Admin, bool) {
	return admindao.GetAdminByID(adminID)
}
